package com.lamp.main;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.lamp.JsonClass.BusinessLists;
import com.lamp.JsonClass.CheckInLocListStatus;
import com.lamp.connection.HttpConnectionManager;
import com.lamp.connection.OnHttpConnectionLoad;
import com.lamp.downloadimage.BitmapCache;
import com.lamp.horizontal.PullToRefreshListView;
import com.lamp.horizontal.PullToRefreshListView.OnRefreshListener;
import com.lamp.listadapter.CheckInAdapter;

public class CheckInActivity extends Activity implements LocationListener {
	private ListView list;
	private List<BusinessLists> businessList = new ArrayList<BusinessLists>();
	private static final BitmapCache bitmapCache = new BitmapCache();
	private Location currentLocation;
	HttpConnectionManager manager;
	List<NameValuePair> params;
	EditText searchET;
	boolean complateRequest = false;

	public void setBusinessList(List<BusinessLists> businessList) {
		this.businessList = businessList;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.checkin);
		list = (ListView) findViewById(R.id.checkinLV);
		manager = new HttpConnectionManager();
		params = new ArrayList<NameValuePair>();
		View footerView = ((LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
				R.layout.checkin_footer, null, false);
		list.addFooterView(footerView);
		Criteria locCriteria = new Criteria();
		locCriteria.setAccuracy(Criteria.ACCURACY_FINE);
		LocationManager locMan = (LocationManager) getSystemService(LOCATION_SERVICE);
		locMan.requestLocationUpdates(
				locMan.getBestProvider(locCriteria, true), 2000, 25, this);

		currentLocation = locMan.getLastKnownLocation(locMan.getBestProvider(
				locCriteria, true));
		searchET = (EditText) findViewById(R.id.searchET);

		LinearLayout addBusiness = (LinearLayout) findViewById(R.id.addBusLT);
		addBusiness.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// add new business
			}
		});
		request();
	}

	private void request() {

		params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("Token", LoginActivity.Token));

		params.add(new BasicNameValuePair("Latitude", String
				.valueOf(currentLocation.getLatitude())));
		params.add(new BasicNameValuePair("Longitude", String
				.valueOf(currentLocation.getLongitude())));
		params.add(new BasicNameValuePair("Radius", String.valueOf(0.4)));
		params.add(new BasicNameValuePair("Skip", Integer.toString(0)));
		params.add(new BasicNameValuePair("Take", Integer.toString(30)));
		manager.sentRequest(
				"http://www.lamp.mn/lamp/webservices/getCheckInLocLists.php",
				params, new OnHttpConnectionLoad() {

					@Override
					public void onHttpConnectionFailed() {
						// TODO Auto-generated method stub

					}

					@Override
					public void onHttpConnectionExecuted(String json) {
						final CheckInLocListStatus checkInLocListStatus = new CheckInLocListStatus();
						final List<BusinessLists> businessList = new ArrayList<BusinessLists>();
						try {
							JSONObject JsonLocListStatus = new JSONObject(json);
							checkInLocListStatus
									.setStatusCode(JsonLocListStatus
											.getInt("StatusCode"));
							checkInLocListStatus.setTotal(JsonLocListStatus
									.getInt("Total"));
							JSONArray JsonFriendList = JsonLocListStatus
									.getJSONArray("BusinessLists");
							for (int i = 0; i < JsonFriendList.length(); i++) {
								BusinessLists businessListItem = new BusinessLists();
								businessListItem.setBusinessId(JsonFriendList
										.getJSONObject(i).getInt("BusinessId"));
								businessListItem.setCategoryId(JsonFriendList
										.getJSONObject(i).getInt("CategoryId"));
								businessListItem.setBusinessName(JsonFriendList
										.getJSONObject(i).getString(
												"BusinessName"));
								businessListItem.setPhoto(JsonFriendList
										.getJSONObject(i).getString("Photo"));
								businessListItem.setLatitude(JsonFriendList
										.getJSONObject(i).getDouble(
												("Latitude")));
								businessListItem.setLongitude(JsonFriendList
										.getJSONObject(i)
										.getDouble("Longitude"));
								businessListItem.setCategoryName(JsonFriendList
										.getJSONObject(i).getString(
												"CategoryName"));
								businessListItem
										.setPromotionCount(JsonFriendList
												.getJSONObject(i).getInt(
														"PromotionCount"));
								businessList.add(businessListItem);
							}
							checkInLocListStatus.setBusinessLists(businessList);
						} catch (JSONException e1) {
							e1.printStackTrace();
						}
						searchET.addTextChangedListener(new TextWatcher() {

							public void onTextChanged(CharSequence s,
									int start, int before, int count) {

							}

							public void beforeTextChanged(CharSequence s,
									int start, int count, int after) {
								// TODO Auto-generated method stub

							}

							public void afterTextChanged(Editable s) {
								CharSequence text = searchET.getText();
								int size = text.length();
								if (size != 0) {
									List<BusinessLists> listSe = new ArrayList<BusinessLists>();
									for (BusinessLists business : businessList) {
										String halfName;
										if (business.getBusinessName().length() >= size) {
											halfName = business
													.getBusinessName()
													.substring(0, size);
											halfName = halfName.toLowerCase();
											String text1 = text.toString()
													.toLowerCase();
											if (halfName.equals(text1)) {
												listSe.add(business);
											}
										}
									}
									ArrayAdapter<BusinessLists> checkinAdapter = new CheckInAdapter(
											CheckInActivity.this, listSe,
											bitmapCache);
									list.setAdapter(checkinAdapter);
								} else {
									ArrayAdapter<BusinessLists> checkinAdapter = new CheckInAdapter(
											CheckInActivity.this, businessList,
											bitmapCache);
									list.setAdapter(checkinAdapter);

								}
							}
						});
						LinearLayout progress = (LinearLayout) findViewById(R.id.chechinProg);
						progress.setVisibility(View.GONE);
						LinearLayout empty = (LinearLayout) findViewById(R.id.chekinEmpty);
						if (checkInLocListStatus.getTotal() != 0)
							empty.setVisibility(View.GONE);
						ArrayAdapter<BusinessLists> checkinAdapter = new CheckInAdapter(
								CheckInActivity.this, businessList, bitmapCache);
						list.setAdapter(checkinAdapter);
						setBusinessList(businessList);
						complateRequest = true;
					}
				});

	}

	private class GetDataTask extends AsyncTask<Void, Void, String[]> {

		@Override
		protected String[] doInBackground(Void... params) {
			// Simulates a background job.

			request();
			complateRequest = false;
			while (!complateRequest) {
				try {
					Thread.sleep(300);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(String[] result) {
			// mListItems.addFirst("Added after refresh...");

			// Call onRefreshComplete when the list has been refreshed.
			PullToRefreshListView listPull = (PullToRefreshListView) findViewById(R.id.checkinLV);
			listPull.onRefreshComplete();

			super.onPostExecute(result);
		}
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

}
